// 导入three.js
import * as THREE from "three";
// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
// 导入GUI
import { GUI } from "three/examples/jsm/libs/lil-gui.module.min.js"
// 导入hdr加载器
import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader.js"
// 导入gltf加载器
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"
// 导入draco解码器
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js"
// 导入补间动画tween库
import * as TWEEN from "three/examples/jsm/libs/tween.module.js"

// 创建场景
const scene = new THREE.Scene()
// scene.background = new THREE.Color("#c6c6c6")
// 创建相机
const camera = new THREE.PerspectiveCamera(
  45, // 视角
  window.innerWidth / window.innerHeight, //宽高比
  0.1, // 近平面
  1000 // 远平面
)

// 创建渲染器
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight) // 设置渲染器宽高
document.body.appendChild(renderer.domElement) // 将渲染器添加到body中

// 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true // 开启阻尼
controls.dampingFactor = 0.05 // 阻尼系数

// 设置相机位置
camera.position.z = 15
camera.position.y = 4
camera.position.x = 2
camera.lookAt(0, 0, 0)

// 添加世界辅助坐标器
const axisHelper = new THREE.AxesHelper(5)
scene.add(axisHelper)

function init() {
  controls.update() // 更新控制器
  requestAnimationFrame(init);
  renderer.render(scene, camera) // 渲染场景和相机
  // 更新tween
  TWEEN.update()
}

init() //初始化
// 创建GUI
const gui = new GUI()

// 加载UV贴图
const uvTexture = new THREE.TextureLoader().load("./image/UVtest.png")

// 创建一个平面
const planeGeometry = new THREE.PlaneGeometry(2, 2)
console.log(planeGeometry)
const planeMaterial = new THREE.MeshBasicMaterial({
  // color: "#f00",
  map: uvTexture
})
const plane = new THREE.Mesh(planeGeometry, planeMaterial)
plane.position.x = -2
scene.add(plane)

// 创建顶点的几何体
const geometry = new THREE.BufferGeometry()
console.log(geometry)
// 使用索引绘制
const vertices = new Float32Array([
  -1.0, -1.0, 0.0,
  1.0, -1.0, 0.0,
  1.0, 1.0, 0.0,
  -1.0, 1.0, 0.0
])
// 创建顶点属性
geometry.setAttribute("position",new THREE.BufferAttribute(vertices, 3))
// 新建索引
const indices = new Uint16Array([
  0, 1, 2,
  0, 2, 3
])
// 创建索引属性
geometry.setIndex(new THREE.BufferAttribute(indices, 1))

// 设置UV坐标
const uv = new Float32Array([
  0.0, 0.0,
  1.0, 0.0,
  1.0, 1.0,
  0.0, 0.0
])
// 创建uv属性
geometry.setAttribute("uv", new THREE.BufferAttribute(uv, 2))

// 创建材质
const material = new THREE.MeshBasicMaterial({
  map: uvTexture
})
// 创建网格
const mesh = new THREE.Mesh(geometry, material)
mesh.position.x = 2
scene.add(mesh)
